package com.molichuxing.services.infrastructure.service.impl;

import com.alibaba.fastjson.JSON;
import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.services.infrastructure.bean.CarBean;
import com.molichuxing.services.infrastructure.bean.MaintenanceBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.MaintenanceMapper;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.dto.response.MaintenanceDto;
import com.molichuxing.services.infrastructure.service.MaintenanceService;
import com.molichuxing.services.property.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 保养表 服务实现类
 * </p>
 *
 * @author xuelin yi
 * @since 2019-09-23
 */
@Service("maintenanceService")
public class MaintenanceServiceImpl implements MaintenanceService {

    private static final Logger log = Logger.getLogger(MaintenanceServiceImpl.class);

    @Resource
    private MaintenanceMapper maintenanceMapper;

    @Override
    public Paged<MaintenanceDto> getMaintenancePage(Map<String, Object> map, Integer pageNum, Integer pageSize) {
        log.info("根据条件查询保养列表。map ： ["+ map +"]");
        Paged<MaintenanceDto> paged = new Paged<>();
        int count = maintenanceMapper.getMaintenancePageCount(map);
        if(count <= 0) {
            return paged;
        }
        List<MaintenanceBean> result = maintenanceMapper.getMaintenancePage(map, pageNum, pageSize);
        log.info("根据条件查询保养列表 出参：result： "+ JSON.toJSONString(result));
        paged.setList(Convert.toMaintenanceDto(result));
        paged.setTotal(count);
        paged.setPageSize(pageSize);
        return paged;
    }

    @Override
    public Integer getCount(MaintenanceTabEnum maintenanceTabEnum) {
        Map<String, Object> map = new HashMap<>();
        if(maintenanceTabEnum == MaintenanceTabEnum.AUDITED) {
            List<Integer> statusList=new ArrayList<>();
            statusList.add(MaintenanceStatusEnum.AUDITED.getValue());
            map.put("statusList",statusList);
            map.put("type",null);
        }else {
            List<Integer> statusList=new ArrayList<>();
            statusList.add(MaintenanceStatusEnum.WAITING_MAINTENANCE.getValue());
            statusList.add(MaintenanceStatusEnum.AUDIT_REJECTED.getValue());
            map.put("statusList",statusList);
            map.put("type",null);
        }
        return maintenanceMapper.getMaintenancePageCount(map);
    }

    @Override
    public MaintenanceDto getMaintenance(Integer maintenanceId) {
        return Convert.toMaintenanceDto(maintenanceMapper.getById(maintenanceId));
    }

    @Override
    public MaintenanceDto getMaintenanceByuserId(Integer userId) {
        return Convert.toMaintenanceDto(maintenanceMapper.getMaintenanceByuserId(userId));
    }
   
    @Override
    public List<MaintenanceDto> getMaintenanceByorderCodes(List<Long> orderCodes, Integer userId) {
    	return Convert.toMaintenanceDto(maintenanceMapper.getMaintenanceByorderCodes(orderCodes,userId));
    }

    /**
     *  应保养&待审核
     * @param status
     * @return
     */
    @Override
    public Integer getMaintenancePendCount(Integer status) {
        return maintenanceMapper.getMaintenancePendCount(status);
    }

    /**
     * 根据车辆id查询 最新一条保养信息
     * @param carId
     * @return
     */
    @Override
    public MaintenanceDto getOneMaintenanceByCarId(Integer carId) {
        return  Convert.toMaintenanceDto(maintenanceMapper.getOneMaintenanceByCarId(carId));
    }

    /**
     * 创建保养信息 返回id
     * @param maintenanceDto
     * @return
     */
    @Override
    public Integer createMaintenance(MaintenanceDto maintenanceDto) {
        MaintenanceBean maintenanceBean = Convert.toMaintenanceBean(maintenanceDto);
        maintenanceMapper.createMaintenance(maintenanceBean);
        return maintenanceBean.getId();
    }

    /**
     * 修改保养信息
     * @param maintenanceDto
     * @return
     */
    @Override
    public int updateMaintenanceById(MaintenanceDto maintenanceDto) {
        return maintenanceMapper.updateMaintenanceById(Convert.toMaintenanceBean(maintenanceDto));
    }

    @Override
    public Boolean updateMaintenanceReturnCar(Integer carId) {
        Integer result = maintenanceMapper.updateMaintenanceReturnCar(carId);
        if(result > 0) {
            return true;
        }
        return false;
    }

    /**
     * 修改保养状态
     * @param id
     * @param maintenanceStatusEnum
     * @return
     */
    @Override
    public int updateMaintenanceStatusById(Integer id, MaintenanceStatusEnum maintenanceStatusEnum) {
        return maintenanceMapper.updateMaintenanceStatusById(id,maintenanceStatusEnum.getValue());
    }

    @Override
    public void importMaintenanceData() {
        List<HashMap<String,Object>> result = maintenanceMapper.importMaintenanceData();
        System.out.println(result);
        Map<String, HashMap<String,Object>> hashMap = new HashMap<>();
        for(HashMap map: result) {
           // String sql = "insert into cars_maintenance_log ";
            if(null != hashMap.get(map.get("vin"))) {
                if(map.get("times").toString().compareTo(hashMap.get(map.get("vin")).get("times").toString()) > 0){
                    hashMap.put(map.get("vin").toString(), map);
                }
            }else {
                hashMap.put(map.get("vin").toString(), map);
            }
        }
        System.out.println(hashMap);
        Map<String,Integer> idMap = new HashMap<>();
        int mainId = 1;
        for(String set : hashMap.keySet()) {
            HashMap<String,Object> hashMapParam = hashMap.get(set);
            String sql = "insert into cars_maintenance(id,order_code,status,user_id,code,car_id,maintainable_mileage,over_mileage,maintainable_date,purchase_date,count) " +
                    "value('"+mainId+"','"+hashMapParam.get("order_code")+"','"+hashMapParam.get("status")+"','"+hashMapParam.get("user_id")+"','"+hashMapParam.get("maintenance_code")+"','"+hashMapParam.get("id")+"','"+hashMapParam.get("maintainable_mileage")+"','"+hashMapParam.get("over_mileage")+"','"+hashMapParam.get("maintainable_date")+"','"+hashMapParam.get("purchase_date")+"','"+hashMapParam.get("times")+"');";
            append(sql);
            idMap.put(hashMapParam.get("vin").toString(),mainId);
            mainId++;
        }

        for(HashMap<String,Object> list : result) {
            String sql = "insert into cars_maintenance_log(maintenance_id,order_code,car_id,user_id,user_type,maintainable_mileage,actual_maintain_mileage," +
                    "maintainable_date,actual_maintain_date,store_name,type,maintenance_url,settlement_url,submit_member_id,check_date,submit_date," +
                    "operation_type,operation_id,status,count,purchase_date,reject_reason) " +


                    "value('"+idMap.get(list.get("vin"))+"','"+list.get("order_code")+"','"+list.get("id")+"','"+list.get("user_id")+"','2'" +
                    ",'"+list.get("maintainable_mileage")+"','"+list.get("actual_maintain_mileage")+"','"+list.get("maintainable_date")+"'," +
                    "'"+list.get("actual_maintain_date")+"','"+list.get("store_name")+"','"+list.get("type")+"','"+list.get("maintenance_url")+"'," +
                    "'[\""+list.get("settlement_url")+"\"]','"+list.get("submit_member_id")+"','"+list.get("check_date")+"'," +
                    "'"+list.get("submit_date")+"','"+1+"','1035'," +
                    "'"+list.get("status")+"','"+list.get("count")+"','"+list.get("purchase_date")+"'," +
                    "'"+list.get("reject_reason")+"');";
            appendLog(sql);
        }
    }

    public static void append(String content) {
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter("C:\\Users\\xuelin yi\\Desktop\\sql.txt", true);
            writer.write(content+"\r\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void appendLog(String content) {
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter("C:\\Users\\xuelin yi\\Desktop\\sqlLog.txt", true);
            writer.write(content+"\r\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
